var openid = '';
$(function() {
	getopenid();
});

function getopenid() {
	openid = window.localStorage.getItem("openid");
	if(openid == null || openid == undefined || openid == '') {
		this.getCode();
	}
}

function getCode() {
	var code = Common.queryGetParam('code');
	if(code == null || code == undefined || code == '') {
		location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx95bdc635798fcfe4&redirect_uri=https%3a%2f%2fapi.fenful.com%2ffenful%2fh5%2frecharge.html&response_type=code&scope=snsapi_base#wechat_redirect";
	    return;
	}
	var paramStr = {};
	paramStr.code = code;
	var params = {};
	params.paramStr = JSON.stringify(paramStr);
	Common.ajaxWithParam("/fenful/api/v1/common/getWxUserOpenId", params, function(data) {
		console.log(data);
		window.localStorage.setItem("openid", data.openid);
	});
}

function createOrder() {
	var openid = window.localStorage.getItem("openid");

	var paramStr = {};
	paramStr.phoneNum = $('#phoneNum').val();
	paramStr.openid = openid;
	paramStr.totalAmount = $('#amount').val();
    paramStr.typeId ="4";
	var params = {};
	params.paramStr = JSON.stringify(paramStr);

	Common.ajaxWithParam("/fenful/api/v1/common/weixinCreateOrder", params, function(data) {
        console.log(data);
        var paramStr = {};
		paramStr.appId = data.appId;
		paramStr.timeStamp = data.timeStamp;
		paramStr.nonceStr = data.nonce_str;
		paramStr.package = data.prepay_id;
		paramStr.signType = data.signType;
		paramStr.paySign = data.sign;
		recharge(paramStr);
	});

}

function recharge(paramStr) {

	WeixinJSBridge.invoke(
		'getBrandWCPayRequest', {
			"appId": paramStr.appId, //公众号名称，由商户传入 
			"timeStamp": paramStr.timeStamp, //时间戳，自1970年以来的秒数
			"nonceStr": paramStr.nonceStr, //随机串     
			"package": paramStr.package,
			"signType": paramStr.signType, //微信签名方式：     
			"paySign": paramStr.paySign //微信签名 
		},
		function(result) {
			if(result.err_msg == "get_brand_wcpay_request:cancel") {
				layer.alert("用户取消了充值！");
			} else {
				layer.alert("充值成功！");
				//跳转页面
				location.href = "http://"+window.location.host+"/fenful/h5/rechargeInfo.html?phoneNum="+$('#phoneNum').val();
			}
		}
	);
}

function goInfo(){
	var phoneNum = $('#phoneNum').val();
	if(phoneNum ==null ||phoneNum ==''){
		console.log("phoneNum为空");
		mui.toast("请输入手机号");
	}else{
		localStorage.setItem("phoneNum",phoneNum);
    	location.href = "http://"+window.location.host+"/fenful/h5/rechargeInfo.html?phoneNum="+$('#phoneNum').val();
	}
	
}
